package jumpingnotes.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import jumpingnotes.dao.BookDAO;
import jumpingnotes.dao.Sorter;
import jumpingnotes.dao.SorterHelper;
import jumpingnotes.model.Audio;
import jumpingnotes.model.Book;

public class BookHibernateDAO extends GenericHibernateDAO<Book> implements BookDAO
{
	public BookHibernateDAO()
	{
		super(Book.class);
	}

	public List<Book> findByKeyword(final String keyword, final int firstResult, final int maxResults, final Sorter sorter)
	{
		return (List<Book>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("from Book b where b.author like :author or b.resourceName like :name order by b.resourceId desc")
					.setString("author", "%"+keyword+"%").setString("name", "%"+keyword+"%");
				//SorterHelper.addSorter(query, sorter);
				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);								
				return query.list();
			}
		}, true);			
	}
	
	public Long getCount()
	{
		return (Long) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select count(*) from Book b");							
				return query.uniqueResult();
			}
		}, true);	
	}
	
	public Long getCountByKeyword(final String keyword)
	{
		return (Long) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select count(*) from Book b where b.author like :author or b.resourceName like :name")
					.setString("author", "%"+keyword+"%").setString("name", "%"+keyword+"%");						
				return query.uniqueResult();
			}
		}, true);	
	}	
}
